package com.neu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neu.base.Result;
import com.neu.entity.DTO.TaskDTO;
import com.neu.entity.ProgressRecord;
import com.neu.entity.Task;
import com.neu.entity.security.LoginUser;
import com.neu.mapper.CommonTaskMapper;
import com.neu.service.CommonProgressRecordService;
import com.neu.service.CommonTaskService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class CommonTaskServiceImpl extends ServiceImpl<CommonTaskMapper, Task> implements CommonTaskService {
    @Autowired
    private CommonProgressRecordService progressRecordService;

    @Override
    public Result updateProgress(TaskDTO taskDTO) {
        Task task = new Task();
        BeanUtil.copyProperties(taskDTO, task);
        Integer progress = taskDTO.getProgress();
        if (progress == 100) {
            //如果任务状态是已完成
            task.setTaskStatus("2");
        } else if (progress > 0) {
            //如果任务状态是进行中
            task.setTaskStatus("1");
        } else {
            //如果任务状态是未开始
            task.setTaskStatus("0");

        }
        task.setUpdateTime(LocalDateTime.now());
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        task.setUpdateId(user.getUserId());
        this.updateById(task);

        //更新进度记录表
        ProgressRecord progressRecord = new ProgressRecord();
        progressRecord.setRecordId(UUID.randomUUID().toString().replace("-", ""));
        progressRecord.setTaskId(task.getTaskId());
        progressRecord.setProgress(progress);
        progressRecord.setRecordTime(LocalDateTime.now());
        progressRecordService.save(progressRecord);
        return Result.success();
    }
}
